package com.ls.lserp.modules.order.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.order.entity.SpecimenProduction;
import com.ls.lserp.modules.order.service.SpecimenProductionService;
import com.ls.lserp.modules.setting.entity.CompanyUser;

import freemarker.template.Configuration;
import groovy.util.ResourceException;
import org.springframework.web.servlet.support.RequestContext;

@Controller
@RequestMapping(value = "${adminPath}/specimen/production")
public class SpecimenProductionController extends BaseController {

	// 保存 编辑 删除 方法
	@Autowired
	private SpecimenProductionService specimenProductionService;

    @Autowired
	Configuration freemarkerConfiguration;

	@ModelAttribute
	public SpecimenProduction get(@RequestParam(required = false) String id) {

		// 判断id是否为空
		if (StringUtils.isNotBlank(id)) {

			// 执行查询语句 查询基本信息
			return specimenProductionService.getSample(Long.parseLong(id));
		} else {

			// 若为空，实例化
			return new SpecimenProduction();
		}
	}

	/**
	 * @Title: 画面跳转用
	 * @return url
	 */
	@RequiresPermissions("specimen:production:view")
	@RequestMapping(value = { "" })
	public String list(Model model) {
		CompanyUser companyUser = new CompanyUser();
		companyUser.setGroupId(StringUtils.toLong(ResourcesUtil.getConfig("group_id_sample")));
		model.addAttribute("sampleUserList", specimenProductionService.findSampleUserList(companyUser));
		// 返回页面地址
	    return "modules/order/specimenProduction";
	}
	
	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param specimenProduction
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws ResourceException
	 */
	@RequiresPermissions("specimen:production:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(SpecimenProduction specimenProduction, HttpServletRequest request, HttpServletResponse response,
			Model model) throws ResourceException {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "specimenProduction");
		
		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		searchParam.append("&sampleRequestNo=");
		searchParam.append(specimenProduction.getSampleRequestNo());
		searchParam.append("&styleNo=");
		searchParam.append(specimenProduction.getStyleNo());
		searchParam.append("&styleNameCn=");
		searchParam.append(specimenProduction.getStyleNameCn());
		searchParam.append("&dateFrom=");
		searchParam.append(specimenProduction.getDateFrom());
		searchParam.append("&dateTo=");
		searchParam.append(specimenProduction.getDateTo());
		searchParam.append("&sampleUserId=");
		searchParam.append(specimenProduction.getSampleUserId());
		searchParam.append("&tabPageStatus=");
		searchParam.append(specimenProduction.getTabPageStatus());
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
		
		// 查询一览页面数据
		Page<SpecimenProduction> page = specimenProductionService.findList(new Page<SpecimenProduction>(request, response),specimenProduction);
		String strUri = request.getContextPath() + Global.getAdminPath();
		String strHtml = "";
		try{
			Map<String, Object>  map = new HashedMap();
			map.put("adminUri",strUri);
			map.put("specimenProductions",page.getList());
			map.put("pageNo",page.getPageNo());
			map.put("pageSize",page.getPageSize());
			map.put("springMacroRequestContext", new RequestContext(request));
			strHtml = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate("specimenProduction.ftl"), map);
		}
		catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
		}
		
		listMap.put("specimenProduction", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}
	
	/**
     * 进入查看页面
     * @param user
     * @param model
     * @return
     */
    @RequiresPermissions("specimen:production:view")
    @RequestMapping(value = "show")
    public String show(SpecimenProduction specimenProduction, Model model) {
    	specimenProduction = specimenProductionService.getSample(specimenProduction.getId());
        // 将查询结果赋值mvc model层返回jsp页面
        model.addAttribute("specimenProduction", specimenProduction);
        
        // 返回页面地址
        return "modules/order/specimenProductionShow";
    }

	/**
	 * 进入编辑页面
	 * @param specimenProduction
	 * @param model
	 * @return
	 */
	@RequiresPermissions("specimen:production:edit")
	@RequestMapping(value = "form")
	public String form(SpecimenProduction specimenProduction,RedirectAttributes redirectAttributes, Model model,HttpSession session) {
		
		specimenProduction.setOldSamId(specimenProduction.getSamId());
	    	
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("specimenProduction", specimenProduction);
		
		// 返回页面地址
		return "modules/order/specimenProductionCreate";
	}
	

	/**
	 * 上传文件画面
	 * @param specimenProduction
	 * @param model
	 * @return
	 */
	@RequiresPermissions("specimen:production:view")
	@RequestMapping(value = "uploadFileImage")
	public String uploadFileImage(SpecimenProduction specimenProduction,Model model,HttpSession session) {
		
	    	
		model.addAttribute("id", specimenProduction.getId());
		model.addAttribute("ftpFile", "/specimenProduction");
		//来源
		model.addAttribute("sourceKbn", "specimenProduction");
		
		// 返回页面地址
		return "modules/order/uploadFile";
	}
	
	/**
	 * 上传文件画面
	 * @param specimenProduction
	 * @param model
	 * @return
	 */
	@RequiresPermissions("specimen:production:edit")
	@RequestMapping(value = "saveFile")
	public String saveFile(SpecimenProduction specimenProduction,HttpServletRequest request, Model model, HttpServletResponse response ) {
		String flag = "false";
		try {
			//保存图片
			specimenProductionService.saveFile(specimenProduction);
			flag = "true";
		} catch (Exception e) {
			//日志打印
			logger.error(e.getMessage(),e);
		}
		// 返回页面地址
		return renderString(response, flag);
	}
	
	/**
	 * 保存信息
	 * @param specimenProduction
	 * @param request
	 * @param model
	 * @param response
	 * @return
	 * @throws ResourceException 
	 */
	@RequiresPermissions("specimen:production:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(SpecimenProduction specimenProduction, HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws ResourceException {
		
		// 判断数据是否删除
		SpecimenProduction newProduction=get(specimenProduction.getId().toString());
		// 判断数据是否删除
        if(newProduction.getSampleRequestNo()==null || BaseEntity.DEL_FLAG_DELETE.equals(newProduction.getDeleteFlag())){
        	// 返回提示信息
        	return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
        }
		
        // 排他处理
	    if(specimenProduction.getVersion()==get(specimenProduction.getId().toString()).getVersion()){
	    	
	    	// 版本号加1
	    	specimenProduction.setVersion(specimenProduction.getVersion()+1);
	    }else{
	    	
	    	// 返回提示信息
	        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
	    }
		     
		    // 保存样品数据
		    specimenProductionService.saveSpecimenProduction(specimenProduction);
					
			// 保存成功返回提示信息
	        return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "pecimenProduct_ok_msg")));
	
	}
	
	/**
	 * 审核页面
	 * @param specimenProduction
	 * @param model
	 * @return
	 */
	@RequiresPermissions("specimen:production:audit")
	@RequestMapping(value = "audit")
	public String audit(SpecimenProduction specimenProduction,RedirectAttributes redirectAttributes, Model model,HttpSession session) {
		
		// 履历一览取得
		AuditInfo auditInfo = new AuditInfo();
		// 样品生产id
		auditInfo.setAuditRelateId(specimenProduction.getId());
		// 阶段（样品)
		auditInfo.setAuditPhaseCd(ResourcesUtil.getConfig("audit_phase_specimen"));
		AuditInfo resultInfo = specimenProductionService.findAuditInfo(auditInfo);
		
		// 待审核状态可以审核
		if(resultInfo.getAuditStatus()==0){
			String strWaitAccept = ResourcesUtil.getConfig("specimen_production_status_wait_accept");
			if(!specimenProduction.getSampleProductionStatus().equals(strWaitAccept)){
				resultInfo.setAuditStatus(1L);
			}
		}
		
		// 样品生产id
		resultInfo.setAuditRelateId(specimenProduction.getId());
		// 样品需求单号
		resultInfo.setAuditRelateNo(specimenProduction.getSampleRequestNo());
		// 阶段
		resultInfo.setAuditPhaseCd(ResourcesUtil.getConfig("audit_phase_specimen"));
		// 样品尺码
		resultInfo.setSizeCd(specimenProduction.getSampleSize());
		// 样品需求单状态
		resultInfo.setSampleRequestStatus(specimenProduction.getSampleRequestStatus());
		// 样品生产状态
		resultInfo.setSampleProductionStatus(specimenProduction.getSampleProductionStatus());
		// 样品需求单id
		resultInfo.setSampleRequestId(specimenProduction.getSampleId());
		
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("auditInfo", resultInfo);
		
		// 返回页面地址
		return "modules/order/auditInfo";
	}
	
	/**
	 * 保存履历信息
	 * @param auditInfo
	 * @param request
	 * @param model
	 * @param response
	 * @return
	 * @throws ResourceException 
	 */
	@RequiresPermissions("specimen:production:edit")
	@RequestMapping(value = "saveAudit")
	@ResponseBody
	public String saveAudit(AuditInfo auditInfo,HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws ResourceException {
		
		// 是否需要更新样品需求状态
		boolean isUpdateStatus = false;
		
		// 判断数据是否删除
		SpecimenProduction newProduction=get(Long.toString(auditInfo.getAuditRelateId()));
		// 判断数据是否删除
		if(newProduction.getSampleRequestNo()==null || BaseEntity.DEL_FLAG_DELETE.equals(newProduction.getDeleteFlag())){
			// 返回提示信息
			return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
		}
		
        // 审核结果已经通过,返回错误提示信息
		AuditInfo pAuditResult = new AuditInfo();
		pAuditResult.setAuditPhaseCd(auditInfo.getAuditPhaseCd());
		pAuditResult.setAuditRelateId(auditInfo.getAuditRelateId());
		if(specimenProductionService.getAuditResult(pAuditResult)>0){
	    	// 返回提示信息
	        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
		}
		
		// 样品生产状态变更,返回错误提示信息
	    if(auditInfo.getSampleProductionStatus().equals(get(Long.toString(auditInfo.getAuditRelateId())).getSampleProductionStatus()) 
	    		&& auditInfo.getSampleProductionStatus().equals(ResourcesUtil.getConfig("specimen_production_status_wait_accept"))){
		    // 设置需求单状态
		    if(auditInfo.getAuditResult()==1){
		    	auditInfo.setSampleProductionStatus(ResourcesUtil.getConfig("specimen_production_status_done"));
		    }else{
		    	auditInfo.setSampleProductionStatus(ResourcesUtil.getConfig("specimen_production_status_wait_sample"));
		    }
	    }else{	
	    	// 返回提示信息
	        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
	    }
		
		// 样品生产状态变更,返回错误提示信息
	    if(auditInfo.getSampleRequestStatus().equals(get(Long.toString(auditInfo.getAuditRelateId())).getSampleRequestStatus()) 
	    		&& auditInfo.getSampleRequestStatus().equals(ResourcesUtil.getConfig("specimen_demand_status_production"))){
	    	
	    	// 表单选择通过并且
	    	if(auditInfo.getAuditResult()==1 && specimenProductionService.isSampleProductionDone(newProduction.getSampleId(),auditInfo.getAuditRelateId())){
	    		// 更新需求单状态
	    		isUpdateStatus = true;
	    		auditInfo.setSampleRequestVersion(newProduction.getVersion()+1);
	    		auditInfo.setSampleRequestStatus(ResourcesUtil.getConfig("specimen_demand_status_done"));
	    	}
	    	
	    }else{	
	    	// 返回提示信息
	        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
	    }
		
	    // 保存样品数据
	    specimenProductionService.saveAuditInfo(auditInfo,isUpdateStatus);
				
		// 保存成功返回提示信息
	    return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "audit_ok_msg")));
	
	}
}